<?php
/**
 * Created by PhpStorm.
 * Use : 订单、支付业务逻辑
 * User: kan.yang@starcor.com
 * Date: 18-12-22
 * Time: 下午12:14
 */

//引入文件
//ini_set('display_errors',1);
include_once dirname(dirname(dirname(dirname(__DIR__)))) . '/logic/backstage/order/buy_order/c_buy_order/logic_order_buy.class.php';
class c_pay_order extends CI_Controller
{

    //购买订单业务类
    private $obj_order_buy_logic = null;
    //物理订单处理类
    private $obj_client_order    = null;

    private $str_class     = null;
    private $str_file      = null;
    private $str_method    = null;
    private $str_directory = null;

    /**
     * 默认构造函数
     */
    public function __construct($str_class = null, $str_file = null, $str_method = null, $str_directory = null)
    {
        parent::__construct($str_class, $str_file, $str_method, $str_directory);
        $this->load->database();
        $this->obj_order_buy_logic = new order_buy_logic($this);
        //初始化在线用户ID
        $this->arr_params['cms_user_id'] = empty($this->arr_params['cms_user_id']) ? $_SESSION['user_id'] : $this->arr_params['cms_user_id'];

        $this->str_class = $str_class;
        $this->str_file = $str_file;
        $this->str_method = $str_method;
        $this->str_directory = $str_directory;
    }

    /**
     * 查询支付订单列表
     */
    public function list_order()
    {
        //分页处理
        $this->_init_page();
        include_once dirname(dirname(dirname(dirname(__DIR__)))) . '/logic/backstage/order/buy_order/c_buy_order/logic_order_buy.class.php';
        $obj_order_buy_logic = new order_buy_logic($this);
        //默认主订单
        //修改初始化查询下拉框一直是主订单 xinxin.deng 2019/1/4 15:40
        //$this->arr_params['cms_order_type'] = empty($this->arr_params['cms_order_type']) ? 0 : $this->arr_params['cms_order_type'];
        $params = $this->arr_params;
        //$params['cms_order_type'] = empty($this->arr_params['cms_order_type']) && !isset($this->arr_params['cms_order_type']) ? 0 : $this->arr_params['cms_order_type'];
        $params['cms_order_type'] = $this->arr_params['cms_order_type'] = empty($this->arr_params['cms_order_type']) ? 0 : $this->arr_params['cms_order_type'];
        $arr_recharge_list = $obj_order_buy_logic->get_list($params,'*',$this->arr_params);
        $order_id_arr = array();
        if($arr_recharge_list['ret'] == 0 && !empty($arr_recharge_list['data_info']))
        {
            foreach($arr_recharge_list['data_info'] as &$val)
            {
                $val['cms_order_type_name']     = $this->config->config['system_pay_order_type'][$val['cms_order_type']];
                $val['cms_order_state_name']    = $this->config->config['system_pay_order_state'][$val['cms_order_state']];
                $val['cms_business_state_name'] = $this->config->config['system_pay_business_state'][$val['cms_business_state']];
                $val['cms_pay_channel_name']    = $this->config->config['system_pay_channel'][$val['cms_pay_channel_id']];
                $val['cms_pay_channel_mode_name'] = $this->config->config['system_pay_channel_mode_type'][$val['cms_pay_channel_mode']];
                $val['cms_pay_order_unpaid_price']= $val['cms_order_price'] - $val['cms_order_price_payed'];
                $order_id_arr[] = $val['cms_id'];
            }
        }
        //操作菜单
        if(empty($params['cms_order_type']) && empty($params['flag_ajax_reurn']))
        {
            $system_file_list = array(
                array(
                    'url'=>'pay/pay_order/c_recharge/item_recharge_edit.php',
                    'class'=>'pay_pay_order_c_recharge_item_recharge_edit',
                    'ajax'=>'',
                    'function'=>'item_recharge_edit',
                    'button_data'=>array(
                        array(
                            'name'=>'详情',
                            'icon'=>'fa-pencil-square-o',
                            'params'=>'',
                            'where' =>'',
                            'bottom'=>true,
                        ),
                    ),
                ),
                array(
                    'url'=>'pay/pay_order/c_pay_order/logistics_desc_edit.php',
                    'class'=>'pay_pay_order_c_pay_order_logistics_desc_edit',
                    'ajax'=>'',
                    'function'=>'logistics_desc_edit',
                    'button_data'=>array(
                        array(
                            'name'=>'物流详情',
                            'icon'=>'fa-pencil-square-o',
                            'params'=>'cms_id',
                            'where' =>'',
                            'bottom'=>true,
                        ),
                    ),
                ),
                array(
                    'url'=>'pay/pay_order/c_pay_order/c_pay.php',
                    'class'=>'pay_pay_order_c_pay_order_c_pay',
                    'ajax'=>'',
                    'function'=>'c_pay',
                    'button_data'=>array(
                        array(
                            'name'=>'支付',
                            'icon'=>'fa-pencil-square-o',
                            'params'=>'',
                            'where' =>'',
                            'bottom'=>true,
                        ),
                    ),
                ),
                array(
                    'url'=>'pay/pay_order/c_pay_order/list_child_order.php',
                    'class'=>'pay_pay_order_c_pay_order_list_child_order',
                    'ajax'=>'',
                    'function'=>'list_child_order_edit',
                    'button_data'=>array(
                        array(
                            'name'=>'子订单',
                            'icon'=>'fa-pencil-square-o',
                            'params'=>'',
                            'where' =>'',
                            'bottom'=>true,
                        ),
                    ),
                ),
            );
            $arr_recharge_list['system_file_list'] = $system_file_list;
        }
        $logistics_params = array(
            'cms_buy_order_id' => $order_id_arr,
        );
        //获取物流信息
        include_once dirname(dirname(dirname(dirname(__DIR__)))) . '/logic/backstage/order/buy_order/c_logistics/logic_logistics.class.php';
        $obj_logistics_logic = new logistics_logic($this);
        //查询数据
        $arr_partner_info = $obj_logistics_logic->get_list($logistics_params,'*');
        if ($arr_partner_info['ret'] == 0 && is_array($arr_partner_info['data_info']) && count($arr_partner_info['data_info']) > 0)
        {
            foreach($arr_recharge_list['data_info'] as &$val)
            {
                foreach ($arr_partner_info['data_info'] as $items)
                {
                    if ($items['cms_buy_order_id'] == $val['cms_id'])
                    {
                        $val['logistics_list'][]     = $items;
                    }
                }

            }
        }
        //输出数据
        $this->load_view_file($arr_recharge_list,__LINE__);
    }

    /**
     * 创建订单
     */
    public function c_order()
    {
        //参数验证
        $this->control_params_check(array(
            'cms_order_type' => array(
                'rule'   => 'in',
                'in' => '0,1,2,3,4,5',
                'reason' => '订单类型非法'
            ),
            'cms_pay_order_code' => array(
                'rule'   => 'notnull',
                'reason' => '购买订单非法'
            )
        ),$this->arr_params);
        //创建支付订单
        $arr_order_add = $this->obj_order_buy_logic->add(array(
            'cms_user_id'         => $this->arr_params['cms_user_id'],
            'cms_order_name'      => empty($this->arr_params['cms_order_name']) ? $this->obj_order_buy_logic->arr_order_type[$this->arr_params['cms_order_type']] : $this->arr_params['cms_order_name'],
            'cms_order_price'     => empty($this->arr_params['cms_order_price']) ? 0.00 : $this->arr_params['cms_order_price'],
            'cms_order_type'      => $this->arr_params['cms_order_type'],
            'cms_order_state'     => '0',
            'cms_business_state'  => '0',
            'cms_order_parent'    => empty($this->arr_params['cms_order_parent']) ? 0 : $this->arr_params['cms_order_parent'],
            'cms_pay_order_code'  => $this->arr_params['cms_pay_order_code'],
            'cms_pay_partner_id'  => '',
            'cms_pay_channel_id'  => '',
            'cms_pay_channel_mode'=> '',
            'cms_pay_mode_type'   => '0',
            'cms_order_price_payed' => 0
        ));
        $this->load_view_file($arr_order_add,__LINE__);
    }

    /**
     * 修改订单
     */
    public function edit_order()
    {
        //参数验证
        $this->control_params_check(array(
            'cms_id'=> array(
                'rule'   => 'notnull',
                'reason' => '支付方用户非法'
            ),
        ),$this->arr_params);
        //修改支付订单
        $arr_order_edit = $this->obj_order_buy_logic->edit($this->arr_params['cms_id'],$this->arr_params);
        $this->load_view_file($arr_order_edit,__LINE__);
    }

    /**
     * 支付订单
     * @return array(
            'ret' => 0 //成功
                     1 //余额不足
                     2 //失败
            'reason'   => '描述信息',
            'data_info'=> array(),
     * )
     */
    public function c_pay()
    {
        //参数验证
        $this->control_params_check(array(
            'cms_user_id'=> array(
                'rule'   => 'notnull',
                'reason' => '支付方用户非法'
            ),
            'cms_order_price' => array(
                'rule'   => 'number',
                'reason' => '订单金额非法'
            ),
            'cms_order_type' => array(
                'rule'   => 'in',
                'in'     => '0,1,2,3,4,5',
                'reason' => '订单类型非法'
            ),
            'cms_pay_order_code' => array(
                'rule'   => 'notnull',
                'reason' => '购买订单非法'
            ),
            'cms_order_price_payed' => array(
                'rule'   => 'notnull',
                'reason' => '本次支付金额非法'
            ),
        ),$this->arr_params);
        $this->flag_ajax_reurn = true;
        //订单处理
        if(empty($this->arr_params['cms_order_id']))
        {//创建订单

            //删除未完成的订单
            //if(!empty($this->arr_params['cms_pay_order_code']) && !empty($this->arr_params['cms_order_parent']))
            $bool_create_flag = true;
            if(!empty($this->arr_params['cms_pay_order_code']))
            {
                $arr_order_info = $this->obj_order_buy_logic->get_one(array('cms_pay_order_code' => $this->arr_params['cms_pay_order_code']),'*');
                if($arr_order_info['ret'] = 0 && !empty($arr_order_info['data_info']))
                {
                    $bool_create_flag = false;
                    $arr_order_info = $arr_order_info['data_info'];
                    if($arr_order_info['cms_business_state'] == 1 && $arr_order_info['cms_order_state'] == 1)
                    {
                        $arr_order_add = array('ret' => 0,'reason' => '【'.$arr_order_info['cms_name'].'】已支付且业务已完成');
                        $this->load_view_file($arr_order_add,__LINE__);
                        return true;
                    }
                }
            }
            //新建订单
            if($bool_create_flag)
            {
                $arr_order_info = $this->_create_order();
            }
        }
        else
        {//校验订单

            $arr_order_info = $this->obj_order_buy_logic->get_one(array('cms_uuid' => $this->arr_params['cms_order_id']),'*');
            if($arr_order_info['ret'] != 0 || empty($arr_order_info['data_info']))
            {
                $arr_order_add = array('ret' => 2,'reason' => '错误:校验订单【' . $this->arr_params['cms_order_id'] . '】不存在');
                $this->load_view_file($arr_order_add,__LINE__);
                return false;
            }
            $arr_order_info = $arr_order_info['data_info'];
        }
        //如果是小样订单，允许积分支付
        if(in_array($arr_order_info['cms_order_type'],array_keys($this->config->config['pay_order_to_integral'])))
        {
            //查询用户可用积分
            include_once dirname(dirname(dirname(dirname(__DIR__)))) . '/logic/backstage/order/buy_order/user_integral/logic_user_integral.class.php';
            $obj_user_integral_logic = new user_integral_logic($this);
            $arr_user_integral = $obj_user_integral_logic->get_one(array('cms_user_id' => $this->arr_params['cms_user_id']));
            if(isset($arr_user_integral['data_info']['cms_integral']) && $arr_user_integral['data_info']['cms_integral'] >= $this->config->config['pay_order_to_integral'][$arr_order_info['cms_order_type']])
            {
                include_once dirname(dirname(dirname(dirname(__DIR__)))) . '/logic/backstage/order/buy_order/integral_detail/logic_integral_detail.class.php';
                $obj_integral_detail_logic = new integral_detail_logic($this);
                $arr_apy_ret = $obj_integral_detail_logic->add(array(
                    'cms_integral_type'   => '1',
                    'cms_user_id'         => $this->arr_params['cms_user_id'],
                    'cms_integral'        => $this->config->config['pay_order_to_integral']['1'][$arr_order_info['cms_order_type']],
                    'cms_incr_decr'       => 1,
                    'cms_extend_id'       => $arr_order_info['cms_id'],
                    'cms_desc'            => '面料小样订单：采用积分支付',
                ));
                unset($obj_integral_detail_logic);
                if($arr_apy_ret['ret'] == 0)
                {
                    $this->obj_order_buy_logic->edit(array('cms_uuid' => $this->arr_params['cms_order_id']),array(
                        'cms_order_state'     => '1',
                        'cms_business_state'  => '1',
                        'cms_pay_mode_type'   => '2',
                    ));
                    //更新物流订单订单状态
                    $this->_update_client_order(array(
                        'cms_order_id'   => $arr_order_info['cms_pay_order_code'],
                        'cms_order_type' => $arr_order_info['cms_order_type'],
                        'cms_state'      => 1,
                    ),$this->arr_params['cms_order_type'],'update_client_oder');
                    $this->load_view_file($arr_apy_ret,__LINE__);
                    return true;
                }
            }
            unset($obj_user_integral_logic,$arr_user_integral);
        }
        //账户余额
        include_once dirname(dirname(dirname(dirname(__DIR__)))) . '/logic/backstage/order/manager/c_manager/order_manager/order_manager.class.php';
        $obj_order_manager = new order_manager($this,'order_manager');
        $arr_user_info = $obj_order_manager->query_only(array('cms_id' => $this->arr_params['cms_user_id']),'cms_user_money');
        $float_user_money = 0.00;
        if($arr_user_info['ret'] == 0 && !empty($arr_user_info['data_info']))
        {
            $float_user_money = $arr_user_info['data_info']['cms_user_money'];
        }
        //验证用账户余额是否充足
        if(($arr_order_info['cms_order_type'] != 0 && $float_user_money < $this->arr_params['cms_order_price']) ||
           ($arr_order_info['cms_order_type'] == 0 && $float_user_money < $this->arr_params['cms_order_price_payed'])
        )
        {//不足

            $arr_order_add = array('ret' => 1,'reason' => '警告:用户余额不足，请充值','data_info' => $arr_order_info);
        }
        else
        {//充足

            //更新账户余额

            $obj_order_manager->edit(array(
                'set' => array(
                    'cms_user_money' => $float_user_money - $this->arr_params['cms_order_price'],
                ),'where' => array(
                    'id' => $this->arr_params['cms_user_id'],
                ),
            ));
            //更新订单状态
            $float_order_payed = $this->arr_params['cms_order_price_payed'] + $arr_order_info['cms_order_price_payed'];
            $str_state = 1;
            if($arr_order_info['cms_order_type'] == 0)
            {
                if($arr_order_info['cms_order_price'] != $float_order_payed)
                {
                    $str_state = 0;
                }
                else
                {//主订单完成，添加积分

                    include_once dirname(dirname(dirname(dirname(__DIR__)))) . '/logic/backstage/order/buy_order/integral_detail/logic_integral_detail.class.php';
                    $obj_integral_detail_logic = new integral_detail_logic($this);
                    $obj_integral_detail_logic->add(array(
                        'cms_integral_type'   => '1',
                        'cms_user_id'         => $this->arr_params['cms_user_id'],
                        'cms_integral'        => $this->config->config['pay_order_to_integral']['1'][$arr_order_info['cms_order_type']],
                        'cms_incr_decr'       => 0,
                        'cms_extend_id'       => $arr_order_info['cms_id'],
                        'cms_desc'            => '主订单完成，添加积分',
                    ));
                }
            }
            $this->obj_order_buy_logic->edit(array('cms_id' => $arr_order_info['cms_id']),array(
                'cms_order_state'     => $str_state,
                'cms_business_state'  => $str_state,
                'cms_pay_mode_type'   => '0',
                'cms_order_price_payed'=> strval($float_order_payed),
            ));
            //更新物流订单订单状态
            $this->_update_client_order(array(
                'cms_order_id'   => $arr_order_info['cms_pay_order_code'],
                'cms_order_type' => $arr_order_info['cms_order_type'],
                'cms_state'      => $str_state,
            ),$this->arr_params['cms_order_type'],'update_client_oder');
            //返回参数
            $arr_order_add = array('ret' => 0,'reason' => '支付成功');
        }
        $this->load_view_file($arr_order_add,__LINE__);
        return true;
    }

    /**
     * 订单报价
     */
    public function order_quoted_price()
    {
        $this->control_params_check(array(
            'cms_order_id' => array(
                'rule'   => 'number',
                'reason' => '订单ID非法'
            ),
            'cms_order_type' => array(
                'rule'   => 'in',
                'in'     => '0,1,2,3,4',
                'reason' => '订单类型非法'
            ),
            'cms_order_num' => array(
                'rule'   => 'number',
                'reason' => '订单数量非法'
            ),
            'cms_unit_price' => array(
                'rule'   => 'number',
                'reason' => '订单单价非法'
            ),
        ),$this->arr_params);
        $this->flag_ajax_reurn = true;
        //初始化订单数量
        $this->arr_params['cms_order_num'] = empty($this->arr_params['cms_order_num']) ? 1 : $this->arr_params['cms_order_num'];
        //获取主订单的价格
        if($this->arr_params['cms_order_type'] == 0)
        {
            $arr_order_price   = $this->_update_client_order($this->arr_params,$this->arr_params['cms_order_type'],'get_order_price');
//            $arr_order_price = array(
//                'str_process_type' => 1,
//                'str_basic_price' => '12',
//                'cms_fabric_price' => '50',
//                'float_material_price' => '78',
//            );

            //计算报价
            list($float_price_range,$float_earnest) = $this->_order_price($arr_order_price['str_process_type'],$this->arr_params['cms_order_num']);
            if($arr_order_price['str_process_type'] == 1)
            {//包工包料：(X+Y+Z) * 倍数

                $float_price_range = ($arr_order_price['str_basic_price'] + $arr_order_price['cms_fabric_price'] + $arr_order_price['float_material_price']) * $float_price_range;
            }
            elseif($arr_order_price['str_process_type'] == 2)
            {//半包料：(X+Z) * 倍数

                $float_price_range = ($arr_order_price['str_basic_price'] + $arr_order_price['float_material_price']) * $float_price_range;
            }
            elseif($arr_order_price['str_process_type'] == 3)
            {//清加工：X * 倍数

                $float_price_range = $arr_order_price['float_material_price'] * $float_price_range;
            }
            else
            {//未知

                $float_price_range = $this->arr_params['cms_unit_price'];
            }
            $float_price   = $this->arr_params['cms_order_num'] * $float_price_range;
            $float_earnest = $float_price * $float_earnest;
        }
        else
        {
            $float_price   = $this->arr_params['cms_order_num'] * $this->arr_params['cms_unit_price'];
            $float_earnest = $float_price;
        }
        //更新物理订单
        $this->_update_client_order(array(
            'cms_order_id'   => $this->arr_params['cms_order_id'],
            'cms_order_type' => $this->arr_params['cms_order_type'],
            'cms_price'      => $float_price,
            'cms_amount'     => $this->arr_params['cms_order_num'],
        ),$this->arr_params['cms_order_type'],'update_client_oder');
        //响应客户端
        $this->load_view_file(array(
            'ret' => 0,
            'data_info' => array('price' => sprintf("%0.2f",$float_price),'earnest' => sprintf("%0.2f",$float_earnest)),
            'reason' => '计算订单报价成功'
        ),__LINE__);
    }

    /**
     * 创建订单
     */
    private function _create_order()
    {
        $str_order_name= empty($this->arr_params['cms_order_name']) ? $this->obj_order_buy_logic->arr_order_type[$this->arr_params['cms_order_type']] : $this->arr_params['cms_order_name'];
        $arr_order_add = $this->obj_order_buy_logic->add(array(
            'cms_user_id'         => $this->arr_params['cms_user_id'],
            'cms_order_name'      => $str_order_name,
            'cms_order_price'     => $this->arr_params['cms_order_price'],
            'cms_order_type'      => $this->arr_params['cms_order_type'],
            'cms_order_state'     => '0',
            'cms_business_state'  => '0',
            'cms_order_parent'    => $this->arr_params['cms_order_parent'],
            'cms_pay_order_code'  => $this->arr_params['cms_pay_order_code'],
            'cms_pay_partner_id'  => '',
            'cms_pay_channel_id'  => '',
            'cms_pay_channel_mode'=> '',
            'cms_pay_mode_type'   => '0',
            'cms_order_desc'      => $str_order_name . ':订单金额 ' . $this->arr_params['cms_order_price'] . ' /元',
            'cms_order_price_payed' => 0
        ));
        //创建订单失败
        if($arr_order_add['ret'] != 0)
        {
            $arr_order_add = array('ret' => 2,'reason' => '错误:创建支付订单失败');
            $this->load_view_file($arr_order_add,__LINE__);
            return false;
        }
        //订单ID
        $arr_order_info = $arr_order_add['data_info']['data'];
        $arr_order_info['cms_id'] = $arr_order_add['data_info']['cms_id'];
        return $arr_order_info;
    }

    /**
     * 根据配置计算价格
     */
    private function _order_price($int_process_type,$int_num)
    {
        $float_price_range = 1;
        $arr_order_price = $this->config->config['pay_order_quoted_price'];
        if(!is_array($arr_order_price) || empty($arr_order_price))
        {
            return $float_price_range;
        }
        if(!isset($arr_order_price[$int_process_type]))
        {
            return $float_price_range;
        }
        else
        {
            $arr_order_earnest = $arr_order_price[$int_process_type]['earnest'];
            $arr_order_price   = $arr_order_price[$int_process_type]['range'];
        }
        //遍历匹配价格范围
        foreach($arr_order_price as $k => $v)
        {
            $bool_mate_flag = false;
            $arr_num_range = explode('-',$k);
            if(count($arr_num_range) == 1)
            {
                if($int_num >= $arr_num_range[0])
                {
                    $bool_mate_flag = true;
                }
            }
            else
            {
                if(empty($arr_num_range[0]))
                {
                    if($arr_num_range[1] >= $int_num)
                    {
                        $bool_mate_flag = true;
                    }
                }
                else
                {
                    if($int_num >= $arr_num_range[0] && $arr_num_range[1] >= $int_num)
                    {
                        $bool_mate_flag = true;
                    }
                }
            }
            if($bool_mate_flag)
            {
                $float_price_range = $v;
                break;
            }
        }
        return array($float_price_range,$arr_order_earnest);
    }

    /**
     * 更新物理订单
     * @param array $arr_update_params array(
            'cms_order_id'   => '物理订单ID',
            'cms_order_type' => '物理订单类型',
            'cms_price'      => '订单价格',
            'cms_amount'     => '订单数量',
            'cms_state'      => '订单状态',
     * )
     * @param int    $int_order_type  订单类型
     * @param string $str_action_name 接口名称
     * @return object
     */
    private function _update_client_order($arr_update_params,$int_order_type,$str_action_name)
    {
        $str_tabla_name = $this->_get_client_table($int_order_type);
        $arr_result = $this->auto_load_table('order', 'con_client', 'c_client_order', $str_tabla_name, $str_action_name, $arr_update_params);
        return $arr_result;
    }

    /**
     * 匹配订单类型
     */
    private function _get_client_table($int_order_type)
    {
        switch($int_order_type)
        {
            case 2:
                $str_tabla_name = 'order_model_dress_order';
                break;
            case 3:
                $str_tabla_name = 'order_simple_dress_order';
                break;
            default :
                $str_tabla_name = 'order_client_order';
                break;
        }
        return $str_tabla_name;
    }

} 